package gac.helloworld;


import java.util.ArrayList;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class EditAlarmActivity extends Activity {

	private int mHour, mMinute, mYear, mMonth, mDay, mWarningTime;
	private TextView mTimeDisplay, mDateDisplay, mWarningDisplay;
	private AutoCompleteTextView mDestinationDisplay;
	private CheckBox mCheckBox;
	private String mDestination;
	static final int TIME_DIALOG_ID = 0;
	static final int DATE_DIALOG_ID = 1;
	private AlarmDbAdapter mDbHelper;
	private Long mRowId;
	private Cursor mCursor;
	private boolean isEditing; // if you are editing an existing alarm
	private int mIsOn, checkIfTooLate;
	private MapHandler mMap;
	private PlacesAdapter<String> adapter;
	private ArrayList<String> mSuggestions;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.edit_screen);

		LocationService.setActivity(this);

		mTimeDisplay = (TextView) findViewById(R.id.timeDisplay);
		mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
		mDestinationDisplay = (AutoCompleteTextView) findViewById(R.id.destinationText);
		mWarningDisplay = (TextView) findViewById(R.id.warningText);
		mCheckBox = (CheckBox) findViewById(R.id.checkBox);
		mTimeDisplay.setText("(None)");
		mDateDisplay.setText("(None)");
		//mDestinationDisplay.setText("(None)");
		mWarningDisplay.setText("0 minutes");
		mDestination = "";
		mWarningTime = 0;
		checkIfTooLate = 0;

		mMap = new MapHandler(this);
		mSuggestions = new ArrayList<String>();
		mSuggestions.add("TEST1234");
		adapter = new PlacesAdapter<String>(this);
		//adapter.setNotifyOnChange(true);
		mDestinationDisplay.setAdapter(adapter);
		
		mDestinationDisplay.addTextChangedListener((new TextWatcher() { 
			public void  afterTextChanged (Editable s){ 
				Log.d("seachScreen", "afterTextChanged");
				ArrayList<String> suggestions = mMap.getAutocomplete(mDestinationDisplay.getText().toString());
				adapter.changeItems(suggestions);
				/*for(String x : suggestions){
					adapter.add(x);
				}*/
				adapter.logItems();
			} 
			public void  beforeTextChanged  (CharSequence s, int start, int 
					count, int after){ 
				Log.d("seachScreen", "beforeTextChanged"); 
			} 
			public void  onTextChanged  (CharSequence s, int start, int before, 
					int count) { 
				Log.d("seachScreen", "onTextChanged");
				//adapter.clear();
			}
		}));

		Calendar c = Calendar.getInstance();
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);
		mHour = c.get(Calendar.HOUR_OF_DAY);
		mMinute = c.get(Calendar.MINUTE);
		isEditing = false;
		mIsOn = 1;
		mCheckBox.setChecked(true);

		Intent intent = getIntent();
		if (intent != null) {
			Bundle bundle = intent.getExtras();
			if (bundle != null)
				mRowId = bundle.getLong(AlarmDbAdapter.KEY_ROWID);
		}

		mDbHelper = new AlarmDbAdapter(this);
		mDbHelper.open();
		if (mRowId != null) {
			mCursor = mDbHelper.fetchAlarm(mRowId);
			startManagingCursor(mCursor);
			isEditing = true;
		}

		this.populateFields();
	}

	private void populateFields() {
		if (isEditing) {

			mDestinationDisplay.setText(mCursor.getString(mCursor.getColumnIndexOrThrow(AlarmDbAdapter.KEY_DESTINATION)));
			mDestination = mCursor.getString(mCursor.getColumnIndexOrThrow(AlarmDbAdapter.KEY_DESTINATION));

			int warningTime = mCursor.getInt(mCursor.getColumnIndexOrThrow(AlarmDbAdapter.KEY_WARNTIME));
			if (warningTime != -1) // if there's a warning time
				if(warningTime == 1){
					mWarningDisplay.setText("1 minute");
				}
				else
				{
					mWarningDisplay.setText(warningTime + " minutes");
				}


			mWarningTime = mCursor.getInt(mCursor.getColumnIndexOrThrow(AlarmDbAdapter.KEY_WARNTIME));

			String amPM = "AM";
			mHour = mCursor.getInt(mCursor.getColumnIndexOrThrow(AlarmDbAdapter.KEY_HOUR));
			mMinute = mCursor.getInt(mCursor.getColumnIndexOrThrow(AlarmDbAdapter.KEY_MINUTE));
			String minuteDisplay = "" + mMinute;
			String hourDisplay = "" + mHour;
			if (mHour == 0) {
				hourDisplay = "" + 12;
			}
			if (mHour > 12) {
				hourDisplay = (mHour - 12) + "";
				amPM = "PM";
			}
			if (mMinute < 10) {
				minuteDisplay = "0" + mMinute;
			}
			mTimeDisplay.setText(hourDisplay + ":" + minuteDisplay + " " + amPM);

			mMonth = mCursor.getInt(mCursor.getColumnIndexOrThrow(AlarmDbAdapter.KEY_MONTH));
			mDay = mCursor.getInt(mCursor.getColumnIndexOrThrow(AlarmDbAdapter.KEY_DAY));
			mYear = mCursor.getInt(mCursor.getColumnIndexOrThrow(AlarmDbAdapter.KEY_YEAR));
			mDateDisplay.setText((mMonth + 1) + "/" + mDay + "/" + mYear);

			mIsOn = mCursor.getInt(mCursor.getColumnIndexOrThrow(AlarmDbAdapter.KEY_ISON));

			if(mIsOn == 0)
			{
				mCheckBox.setChecked(false);
			}
			else
			{
				mCheckBox.setChecked(true);
			}

		}
	}

	public void checkBox_click(View v)
	{
		if(mCheckBox.isChecked())
		{
			mIsOn = 1;
		}
		else
		{
			mIsOn = 0;
		}
	}

	public void editTime_Click() {
		showDialog(TIME_DIALOG_ID);
	}

	public void editTime_Click(View v) {
		this.editTime_Click();
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		Calendar c = Calendar.getInstance();
		switch (id) {
		case TIME_DIALOG_ID:
			TimePickerDialog timePick;
			if (isEditing) {
				timePick = new TimePickerDialog(this, mTimeSetListener, mHour, mMinute, false);
			} else {
				timePick = new TimePickerDialog(this, mTimeSetListener, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), false);
			}
			timePick.setTitle("Set Arrival Time");
			return timePick;
		case DATE_DIALOG_ID:
			DatePickerDialog datePick;
			if (isEditing) {
				datePick = new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay);
			} else {
				datePick = new DatePickerDialog(this, mDateSetListener, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
			}
			datePick.setTitle("Set Arrival Date");
			return datePick;
		}
		return null;
	}

	private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			mHour = hourOfDay;
			mMinute = minute;
			updateTimeDisplay();
		}
	};

	private void updateTimeDisplay() {
		String amPM = "AM";
		String hour = "" + mHour;
		String minute = "" + mMinute;
		if (mHour == 0) {
			hour = "" + 12;
		}
		if (mHour > 12) {
			hour = "" + (mHour - 12);
			amPM = "PM";
		}
		if (mMinute < 10) {
			minute = "0" + mMinute;
		}
		mTimeDisplay.setText(hour + ":" + minute + " " + amPM);
	}

	public void editDate_Click() {
		showDialog(DATE_DIALOG_ID);
	}

	public void editDate_Click(View v) {
		this.editDate_Click();
	}

	private void updateDateDisplay() {
		mDateDisplay.setText((mMonth + 1) + "/" + mDay + "/" + mYear);
	}

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;
			updateDateDisplay();
		}
	};

	public void destination_click(View v) {
		this.destination_click();
	}

	public void destination_click() {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);

		alert.setTitle("Set Destination");

		// Set an EditText view to get user input
		final EditText input = new EditText(this);

		if (isEditing) {
			input.setText(mDestination);
		}

		alert.setView(input);
		input.requestFocus();

		alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				String value = input.getText().toString();
				mDestination = value;
				mDestinationDisplay.setText(mDestination);
			}
		});

		alert.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				// Canceled.
			}
		});

		alert.show();
	}

	public void warning_click() {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle("Set Warning Time (in minutes)");

		// Set an EditText view to get user input
		final EditText input = new EditText(this);
		alert.setView(input);
		input.setInputType(InputType.TYPE_CLASS_NUMBER);
		input.requestFocus();
		if (mRowId != null) {
			input.setText(mWarningTime + "");
		}
		alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				String value = input.getText().toString();
				mWarningTime = Integer.parseInt(value);
				if(mWarningTime == 1)
				{
					mWarningDisplay.setText("1 minute");
				}else{
					mWarningDisplay.setText(mWarningTime + " minutes");
				}

			}
		});

		alert.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				// Canceled.
			}
		});

		alert.show();
	}

	public void warning_click(View v) {
		this.warning_click();
	}

	//returns if it's possible to get to the location on time
	//first check if(!(mMap.calculateTime() == 0 && mMap.at00())), then if(mMap.isTimeToLeave())
	public boolean isTripPossible(){
		return true;
	}

	public void saveClick(View v) {
		mMap = new MapHandler (this, mDestination, mHour, mMinute, mMonth, mDay, mYear, mWarningTime);
		mDestination = mDestinationDisplay.getText().toString();
		//check if info is valid (NOTE THAT ISVALIDLOC METHOD HAS NOT BEEN WRITTEN YET)
		if(!mMap.isValidLoc(mDestination)){
			Toast.makeText(this, "Destination is invalid", Toast.LENGTH_SHORT).show();
			return;
		}
		if(! isTripPossible()){
			Toast.makeText(this, "It's too late to get to your destination on time. Did not save.", Toast.LENGTH_SHORT).show();
			return;
		}

		if (!isEditing)
			mDbHelper.createAlarm(mDestination, mHour, mMinute, mWarningTime, mMonth, mDay, mYear, mIsOn);
		else
			mDbHelper.updateAlarm(mRowId, mDestination, mHour, mMinute, mWarningTime, mMonth, mDay, mYear, mIsOn);
		stopManagingCursor(mCursor);
		mDbHelper.close();
		
		Intent i = new Intent(this, LocationService.class);
		Bundle bundle = new Bundle();
		bundle.putInt(AlarmDbAdapter.KEY_MONTH, mMonth);
		bundle.putInt(AlarmDbAdapter.KEY_DAY, mDay);
		bundle.putInt(AlarmDbAdapter.KEY_YEAR, mYear);
		bundle.putInt(AlarmDbAdapter.KEY_HOUR, mHour);
		bundle.putInt(AlarmDbAdapter.KEY_MINUTE, mMinute);
		bundle.putString(AlarmDbAdapter.KEY_DESTINATION, mDestination);
		i.putExtras(bundle);
		startService(i);
		setResult(RESULT_OK);
		finish();
	}

	public void deleteClick(View v) {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle("Delete Alarm");
		alert.setMessage("Are you sure you want to delete this alarm?");
		alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				if (isEditing) {
					mDbHelper.deleteAlarm(mRowId);
					stopManagingCursor(mCursor);
					mDbHelper.close();
				}
				finish();
			}
		});

		alert.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				// Canceled.
			}
		});

		alert.show();
	}
}
